using System;
using System.Threading;
using System.Threading.Tasks;
using MtApi5;

namespace MT5Trade
{
    public class DebugConnection
    {
        public static void TestConnection()
        {
            Console.WriteLine("===== 开始调试连接问题 =====\n");

            // 测试1: 创建MtApi5Client实例
            Console.WriteLine("[1] 创建MtApi5Client实例测试");
            MtApi5Client client = null;
            try
            {
                client = new MtApi5Client();
                Console.WriteLine("  ✓ MtApi5Client创建成功");
                Console.WriteLine($"  - 初始连接状态: {client.ConnectionState}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  ✗ 创建失败: {ex.Message}");
                Console.WriteLine($"  - 异常类型: {ex.GetType().Name}");
                Console.WriteLine($"  - 堆栈: {ex.StackTrace}");
                return;
            }

            // 测试2: 注册事件处理器
            Console.WriteLine("\n[2] 注册事件处理器");
            try
            {
                bool eventFired = false;
                Mt5ConnectionState lastState = Mt5ConnectionState.Disconnected;
                Exception connectionError = null;

                client.ConnectionStateChanged += (sender, e) =>
                {
                    eventFired = true;
                    lastState = e.Status;
                    Console.WriteLine($"  ! 事件触发 - 状态变化: {e.Status}");

                    // 检查是否有额外的错误信息
                    if (e.Status == Mt5ConnectionState.Failed)
                    {
                        Console.WriteLine($"  ! 连接失败");
                    }
                };

                Console.WriteLine("  ✓ 事件处理器注册成功");

                // 测试3: 尝试连接
                Console.WriteLine("\n[3] 测试连接到端口 8228");
                Console.WriteLine($"  - 连接前状态: {client.ConnectionState}");

                try
                {
                    client.BeginConnect(8228);
                    Console.WriteLine("  ✓ BeginConnect调用成功");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"  ✗ BeginConnect失败: {ex.Message}");
                    connectionError = ex;
                }

                // 等待并检查结果
                Console.WriteLine("\n[4] 等待连接结果 (10秒)...");
                for (int i = 0; i < 10; i++)
                {
                    Thread.Sleep(1000);
                    Console.WriteLine($"  {i+1}秒 - 当前状态: {client.ConnectionState}");

                    if (client.ConnectionState == Mt5ConnectionState.Connected)
                    {
                        Console.WriteLine("  ✓ 连接成功!");
                        break;
                    }

                    if (client.ConnectionState == Mt5ConnectionState.Failed)
                    {
                        Console.WriteLine("  ✗ 连接失败!");
                        break;
                    }
                }

                // 最终状态
                Console.WriteLine($"\n[5] 最终结果:");
                Console.WriteLine($"  - 连接状态: {client.ConnectionState}");
                Console.WriteLine($"  - 事件是否触发: {(eventFired ? "是" : "否")}");
                Console.WriteLine($"  - 最后的事件状态: {lastState}");

                if (connectionError != null)
                {
                    Console.WriteLine($"  - 连接错误: {connectionError.Message}");
                }

                // 如果连接成功，尝试获取账户信息
                if (client.ConnectionState == Mt5ConnectionState.Connected)
                {
                    Console.WriteLine("\n[6] 测试API功能");
                    try
                    {
                        var balance = client.AccountInfoDouble(ENUM_ACCOUNT_INFO_DOUBLE.ACCOUNT_BALANCE);
                        Console.WriteLine($"  ✓ 账户余额: {balance}");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"  ✗ 获取账户信息失败: {ex.Message}");
                    }
                }

                // 断开连接
                if (client.ConnectionState == Mt5ConnectionState.Connected)
                {
                    client.BeginDisconnect();
                    Console.WriteLine("\n  已断开连接");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  ✗ 测试过程异常: {ex.Message}");
                Console.WriteLine($"  - 堆栈: {ex.StackTrace}");
            }
            finally
            {
                client = null;
            }

            Console.WriteLine("\n===== 调试完成 =====");
        }

        // 检查MtApi5.dll是否正确加载
        public static void CheckDllLoading()
        {
            Console.WriteLine("\n[DLL检查]");
            try
            {
                var assemblies = AppDomain.CurrentDomain.GetAssemblies();
                foreach (var assembly in assemblies)
                {
                    if (assembly.GetName().Name.Contains("MtApi5"))
                    {
                        Console.WriteLine($"  ✓ 已加载: {assembly.GetName().Name} v{assembly.GetName().Version}");
                        Console.WriteLine($"    位置: {assembly.Location}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  ✗ 检查失败: {ex.Message}");
            }
        }
    }
}